import NProgress from 'nprogress'
import { Notification } from 'element-ui'
import axios from 'axios'
import router from '@/router'
import { getToken } from './authorization'

const BASEURL = '/api'
const service = axios.create({
  // headers:
  baseURL: BASEURL,
  timeout: 300000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    NProgress.start()
    if (getToken()) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    NProgress.done()
    if (response.status === 200) {
      return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    NProgress.done()
    if (error.response) {
      console.error(error.response)
      switch (error.response.status) {
        // 401: 未登录
        case 401:
          Notification.error({
            title: error.response.status || '错误',
            message: '' || error.response.statusText,
            position: 'bottom-right'
          })
          router.replace({
            path: '/login',
            query: { redirect: router.currentRoute.fullPath }
          })
          break
        // 403: token过期
        case 403:
          Notification.error({
            title: error.response.status || '错误',
            message:
              '登录信息已过期，请重新登录！' || error.response.statusText,
            position: 'bottom-right'
          })
          router.push('/login')
          break
        // 404: 请求不存在
        // 500: INTERNAL SERVER ERROR
        case 500:
          Notification.error({
            title: error.response.status || '错误',
            message: '因特网服务错误' || error.response.statusText,
            position: 'bottom-right'
          })
          break
      }
    }
    return Promise.reject(error)
  }
)

export default service
